package leetcode.code0662;

import java.util.HashMap;
import java.util.Map;

import leetcode.IDebug;
import leetcode.helper.tree.TreeNode;

public class Solution2 implements IDebug {

	long ans;
	Map<Integer, long[]> map;

	public int widthOfBinaryTree(TreeNode root) {
		if (root == null) {
			return 0;
		}
		ans = 0;
		map = new HashMap<>();
		check(root, 1, 1);
		return (int) ans;
	}

	private void check(TreeNode root, int h, long index) {
		if (root == null) {
			return;
		}
		long[] val = map.computeIfPresent(h,
				(key, value) -> new long[] { Math.min(value[0], index), Math.max(value[1], index) });
		val = map.computeIfAbsent(h, key -> new long[] { index, index });
		ans = Math.max(ans, (val[1] - val[0] + 1));
		this.check(root.left, h + 1, index << 1);
		this.check(root.right, h + 1, (index << 1) + 1);
	}

	@Override
	public void debug4() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution2 so = new Solution2();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
